package com.hjy.attendance.context;


import com.hjy.attendance.exception.ApiException;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 *
 * @version: 1.0
 * @author: xiejiarong
 * @date: 2020/03/18
 */
public class IMContextHolder {

    public static final String REQUEST_ID = "requestId";
    public static final String OPERATOR = "operator";
    public static final String TOKEN = "token";


    private static final ThreadLocal<Map<String, String>> HOLDER = ThreadLocal.withInitial(
            () -> new HashMap<>(1)
    );

    public static String get(String key) {
        return HOLDER.get().getOrDefault(key, "");
    }

    public static String getOrThrow(String key) throws ApiException {
        return Optional.ofNullable(get(key)).orElseThrow(() -> new ApiException("找不到指定的上下文值,key=" + key));
    }

    public static void set(String key, String value) {
        HOLDER.get().put(key, value);
    }

    public static void clear() {
        HOLDER.remove();
    }

}
